package cn.zh.npro.Activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import cn.zh.npro.Item.CaFItem;
import cn.zh.npro.Item.CaItem;
import cn.zh.npro.Item.OfItem;
import cn.zh.npro.Item.OfgItem;
import cn.zh.npro.Item.RpItem;
import cn.zh.npro.Item.TdItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.Loading;
import cn.zh.npro.Util.ToastUtil;
import cn.zh.npro.bean.GoodsSpec;
import cn.zh.npro.bean.TradeGoods;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class Order extends BaseActivity{

    ImageView fil_back;
    MyApplication mapp;
    String cid="",uid="",user="";

    TextView cliname,paytxt,numtxt,houtxt,sttxt,timtxt,
            totaey,taxtxt,sftxt,tomoney,naphtxt,dadres;
    LinearLayout relin,shlin,stypelin,timlin,sublin;
    EditText obadres,mark;

    JSONArray LinkmanList;
    //判断仓库与配送方式
    String type="0";
    CaFItem caFItem,caFItem1;
    TextView suborder;
    CaItem caItem=null;
    String linkmanid="";
    ArrayList<RpItem> tlist;
    ArrayList<TradeGoods> glist;
    LinearLayout imalin;
    String otype="";
    private Dialog LDialog;
    double total=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        otype=getIntent().getStringExtra("type");
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        System.out.println("--------------------->uid==="+uid);
        user=mapp.getSp().getString("Linkman","");
        cid=mapp.getClID();
        tlist= (ArrayList<RpItem>) getIntent().getSerializableExtra("tlist");
        glist=(ArrayList<TradeGoods>) getIntent().getSerializableExtra("glist");
        initod();
        if (otype.equals("1")){
            getOrded();
        }
        getCdent();
        int ta=0,tb=0;

        for (int j=0;j<tlist.size();j++){
            if (tlist.get(j).getNum()!=0){
                ta=ta+1;
                tb=tb+tlist.get(j).getNum();
                total=Double.parseDouble(tlist.get(j).getPrice_Detail())+total;
            }
            ImageView ima=new ImageView(this);
            Picasso.with(this).load(tlist.get(j).getIndexURL()).error(R.mipmap.noimage).into(ima);
            ima.setPadding(5,5,5,5);
            ima.setAdjustViewBounds(true);
            imalin.addView(ima);
        }
        numtxt.setText("共计"+ta+"种商品"+tb+"件");
        totaey.setText("¥"+total);
        //税费
        double fee= Double.parseDouble(taxtxt.getText().toString());
        //运费
        double trfee= Double.parseDouble(sftxt.getText().toString());
        //总费用
        double tal=fee+trfee+total;
        DecimalFormat format = new DecimalFormat("0.00");
        String p = format.format(new BigDecimal(tal));
        tomoney.setText(p+"");
    }

    public void initod(){
        fil_back=findViewById(R.id.fil_back);
        cliname=findViewById(R.id.cliname);
        paytxt=findViewById(R.id.paytxt);
        numtxt=findViewById(R.id.numtxt);
        houtxt=findViewById(R.id.houtxt);
        sttxt=findViewById(R.id.sttxt);
        timtxt=findViewById(R.id.timtxt);
        totaey=findViewById(R.id.totaey);
        taxtxt=findViewById(R.id.taxtxt);
        sftxt=findViewById(R.id.sftxt);
        tomoney=findViewById(R.id.tomoney);
        relin=findViewById(R.id.relin);
        shlin=findViewById(R.id.shlin);
        stypelin=findViewById(R.id.stypelin);
        imalin=findViewById(R.id.imalin);
        timlin=findViewById(R.id.timlin);
        sublin=findViewById(R.id.sublin);
        obadres=findViewById(R.id.obadres);
        mark=findViewById(R.id.mark);
        naphtxt=findViewById(R.id.naphtxt);
        dadres=findViewById(R.id.dadres);
        suborder=findViewById(R.id.suborder);
        fil_back.setOnClickListener(this);
        relin.setOnClickListener(this);
        shlin.setOnClickListener(this);
        stypelin.setOnClickListener(this);
        timlin.setOnClickListener(this);
        suborder.setOnClickListener(this);
    }



    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.fil_back:
                finish();
                break;
            case R.id.relin:
                String lstr="";
                if (null==LinkmanList){
                    lstr="";
                } else {
                    lstr=LinkmanList.toString();
                }
                Intent intent2=new Intent(Order.this,ReActivity.class);
                intent2.putExtra("ja",lstr);
                startActivityForResult(intent2,2);
                break;
            case R.id.shlin:
                type="0";
                Intent intent=new Intent(Order.this,ConActivity.class);
                intent.putExtra("type",type);
                startActivityForResult(intent,0);
                break;
            case R.id.stypelin:
                type="1";
                Intent intent1=new Intent(Order.this,ConActivity.class);
                intent1.putExtra("type",type);
                startActivityForResult(intent1,1);
                break;
            case R.id.timlin:
                getBir();
                break;
            case R.id.suborder:
                submit();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null==data){
            return;
        }
        switch (requestCode){
            case 0:
                caFItem = (CaFItem) data.getSerializableExtra("ob");
                houtxt.setText(caFItem.getName());
                break;
            case 1:
                caFItem1= (CaFItem) data.getSerializableExtra("ob");
                sttxt.setText(caFItem1.getName());
                break;
            case 2:
                caItem= (CaItem) data.getSerializableExtra("caItem");
                linkmanid=caItem.getLinkmanid();
                naphtxt.setText(caItem.getFullname()+" "+caItem.getMobile());
                dadres.setText(caItem.getAddress());
                break;
        }
    }



    public void getCdent(){
        OkHttpUtils.get(BaseUrl.GetCustomerDetail)
                .params("customerId",cid)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        System.out.println("-------------->获取用户信息=="+s);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONObject Res=js.getJSONObject("Res");
                                JSONObject Customer=Res.getJSONObject("Customer");
                                String id=Customer.getString("ID");
                                String companyName=Customer.getString("companyName");
                                String customerType=Customer.getString("customerType");
                                String customerLevel=Customer.getString("CustomerLevel");
                                String ChargeType=Customer.getString("ChargeType");
                                String address=Customer.getString("address");
                                String joinDate=Customer.getString("joinDate");
                                String province=Customer.getString("province");
                                String city=Customer.getString("city");
                                cliname.setText(companyName);
                                paytxt.setText(ChargeType);
                                LinkmanList = Res.getJSONArray("LinkmanList");
                                for (int i=0;i<LinkmanList.length();i++){
                                    JSONObject ji=LinkmanList.getJSONObject(i);
                                    boolean isMaster=ji.getBoolean("isMaster");
                                    if (isMaster){
                                        linkmanid = ji.getString("linkmanid");
                                        String fullname=ji.getString("fullname");
                                        String mobile=ji.getString("mobile");
                                        String addres=ji.getString("address");
                                        naphtxt.setText(fullname+" "+mobile);
                                        dadres.setText(addres);
                                        caItem=new CaItem(linkmanid,fullname,mobile,addres,true);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }



    public void getBir(){
        TimePickerView pvTime = new TimePickerView.Builder(Order.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                String time = getTime(date2);
                timtxt.setText(time);
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLACK)//确定按钮文字颜色
                .setCancelColor(Color.BLACK)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }


    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    public void submit(){
        String wadre=obadres.getText().toString();
        String tol=total+"";
        String tim=timtxt.getText().toString();
        String tax=taxtxt.getText().toString();
        String trtxt=sftxt.getText().toString();
        String type=sttxt.getText().toString();
        String remark=mark.getText().toString();
        if (null==caItem){
            ToastUtil.showShort(Order.this,"请选择收货地址");
            return;
        }
        if (null==caFItem){
            ToastUtil.showShort(Order.this,"请选择发货仓库");
            return;
        }
        if (null==caFItem1){
            ToastUtil.showShort(Order.this,"请选择配送方式");
            return;
        }
        if (tim.equals("请选择")){
            ToastUtil.showShort(Order.this,"请选择交货日期");
            return;
        }
        if (wadre.equals("")){
            ToastUtil.showShort(Order.this,"请填写物流地址");
            return;
        }

        TdItem tdItem=new TdItem(caFItem.getId(),caItem.getAddress(),wadre,remark,caItem.getMobile(),cid,tol,uid,"0",tim,trtxt,user,tax,caItem.getFullname());
        ArrayList<OfgItem>  ofgItems=new ArrayList<>();
        for (int i=0;i<tlist.size();i++){
            OfgItem ofgItem=new OfgItem(tlist.get(i).getGoodsNo(),tlist.get(i).getGoodsId(),tlist.get(i).getSpecID(),tlist.get(i).getNum()+"",tlist.get(i).getSellPrice(),tlist.get(i).getUnit(),
                    tlist.get(i).getGoodsNo(),tlist.get(i).getTradeSpec(),tlist.get(i).getUnit2(),tlist.get(i).getPrice2(),tlist.get(i).getCount2(),tlist.get(i).getRate2());
            ofgItems.add(ofgItem);
        }
        OfItem  ofItem=new OfItem(tdItem,ofgItems);
        Gson gson=new Gson();
        String json=gson.toJson(ofItem);
        LDialog= Loading.createLoadingDialog(this,"加载中...");
        OkHttpUtils.post(BaseUrl.AddGoodsTrade)
                .postJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        Loading.closeDialog(LDialog);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            String Msg=js.getString("Msg");
                            ToastUtil.showLong(Order.this,Msg);
                            if (State){
                                Intent intent=new Intent(Order.this,MainActivity.class);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });

    }



    //获取订单详情
    public void getOrded(){
        String traId=mapp.getTraId();
        OkHttpUtils.get(BaseUrl.GetTradeDetail)
                .params("tradeId",traId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        System.out.println("------------->获取订单详情===="+s);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONObject Res=js.getJSONObject("Res");
                                JSONObject Trade_TradeList=Res.getJSONObject("Trade_TradeList");

                                String WuliuAdr=Trade_TradeList.getString("WuliuAdr");
                                String YSndTime=Trade_TradeList.getString("YSndTime");
                                String SndTo=Trade_TradeList.getString("SndTo");
                                String Tel=Trade_TradeList.getString("Tel");
                                String Adr=Trade_TradeList.getString("Adr");
                                String WarehouseName=Trade_TradeList.getString("WarehouseName");
                                String WareHouseID=Trade_TradeList.getString("WareHouseID");
                                String Remark=Trade_TradeList.getString("Remark");
                                mark.setText(Remark);
                                timtxt.setText(YSndTime);
                                obadres.setText(WuliuAdr);
                                naphtxt.setText(SndTo+" "+Tel);
                                dadres.setText(Adr);
                                houtxt.setText(WarehouseName);
                                caItem=new CaItem("",SndTo,Tel,Adr,false);
                                caFItem=new CaFItem(WareHouseID,WarehouseName);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }
}
